<!--
 * @Author: guandeshen 295570679@qq.com
 * @Date: 2024-05-20 16:11:07
 * @LastEditors: guandeshen 295570679@qq.com
 * @LastEditTime: 2024-09-23 16:39:14
 * @FilePath: /task-admin/src/views/wbs/index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
-->
<template>
  <div class="container flex h-[calc(100vh-84px)]">
    <div
      class="w-236px h-full bg-[#fff] border-rd-8px shrink-0 mr-24px px-24px py-32px box-border"
    >
      <div class="border-b-1px border-[#ebedf0] pb-16px">
        <h3
          class="text-[#323233] text-16px font-900 flex h-22px items-center flex items-center m-0"
        >
          <span
            class="w-3px h-22px border-rd-1px bg-#4E6BEF block mr-8px"
          ></span>
          {{ $t("common.projectList") }}
        </h3>
      </div>

      <el-input
        class="mb-16px mt-16px"
        v-model="searchName"
        :placeholder="$t('common.searchProject')"
      >
        <template #append>
          <el-button @click="handleSearch" :icon="Search" />
        </template>
      </el-input>

      <el-menu
        active-text-color="#ffd04b"
        class="wbs-menu"
        text-color="#323233"
      >
        <el-sub-menu
          :index="item.id"
          v-for="item in projectAndSite"
          :key="item.id"
        >
          <template #title>
            <span class="ellipsis">{{ item.p_name }}</span>
          </template>
          <template v-if="item?.sites && item?.sites.length > 0">
            <el-menu-item
              v-for="citem in item.sites"
              @click="handleSiteClick(item, citem)"
              :key="citem.id"
              :index="citem.id"
              class="ellipsis box-border w-[100%]"
              >{{ citem.s_name }}</el-menu-item
            >
          </template>
          <el-empty v-else :image-size="40" />
        </el-sub-menu>
      </el-menu>
    </div>
    <div
      v-if="showInfo"
      class="h-full flex-1 flex-col flex w-[calc(100%-300px)]"
    >
      <div
        class="bg-[#fff] h-88px border-rd-8px mb-24px box-border px-24px py-32px flex justify-between"
      >
        <div class="flex justify-between items-center w-[100%]">
          <span class="custom-title flex-1">
            {{ projectInfo?.p_name }}
          </span>
          <div class="flex items-center w-280px justify-end">
            <span class="text-[#323233] text-12px font-500 lh-18px mr-8px"
              >{{ $t("common.progress") }}:</span
            >
            <div class="w-190px">
              <el-progress
                :text-inside="true"
                :stroke-width="24"
                :percentage="projectInfo?.process"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="bg-[#fff] flex-1 border-rd-8px">
        <!-- 列表 -->
        <page-content
          ref="contentRef"
          :stripe="true"
          :content-config="contentConfig"
          @add-click="handleOpenDialog"
          @edit-click="handleEditClick"
          @view-click="handleViewClick"
          :defaultParams="defaultParams"
        >
          <template #status="scope">
            <span
              class="table-status"
              :class="`status_${statusOptions[scope.row.status].value}`"
              >{{ statusOptions[scope.row.status].label }}</span
            >
          </template>

          <template #progress="scope">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="`${scope.row.schedule}%`"
              placement="top"
            >
              <el-progress
                :show-text="false"
                :percentage="scope.row.schedule"
              />
            </el-tooltip>
          </template>
        </page-content>
      </div>
    </div>
    <div v-else class="h-full flex-1 flex-center">
      <div class="flex-center flex-col">
        <svg-icon class="w-400px! h-400px!" icon-class="no-wbs" />
        <p
          class="text-[#323233] text-24px font-900 mt-20px lh-34px mb-16px text-center"
        >
          {{ $t("common.noProjectSelected") }}
        </p>
        <p
          class="text-[#969799] text-16px font-500 lh-22px text-center max-w-[70%]"
        >
          {{ $t("common.PleaseSelectLeftSide") }}
        </p>
      </div>
    </div>

    <!-- 新增表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="890px"
      @close="handleCloseDialog"
    >
      <BasicInfoForm
        ref="basicInfoFormFormRef"
        :disabled="viewType == 2 ? false : true"
        :projectInfo="projectInfo"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">{{
            $t("common.save")
          }}</el-button>
          <el-button @click="handleCloseDialog">{{
            $t("common.cancel")
          }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!--编辑查看弹窗-->
    <el-drawer
      v-model="drawerDialog.visible"
      :title="drawerDialog.title"
      size="1260px"
      @close="handleDrawerCloseDialog"
    >
      <div class="drawer-box">
        <div class="bg-[#F2F3F5] p8 mb-4 flex justify-between">
          <ul class="flex flex-1 justify-between">
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.projectName")
              }}</span>
              <p
                class="text-[#323233] m-0 ellipsis w-[100%] text-16px font-900 lh-24px"
              >
                {{ projectInfoForm?.p_name }}
              </p>
            </li>
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.siteName")
              }}</span>
              <p
                class="text-[#323233] m-0 ellipsis w-[100%] text-16px font-900 lh-24px"
              >
                {{ siteName }}
              </p>
            </li>
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.projectLeader")
              }}</span>
              <p
                class="text-[#323233] m-0 ellipsis w-[100%] text-16px font-900 lh-24px"
              >
                {{ stakeholderObj[projectInfoForm?.p_manager as string] }}
              </p>
            </li>
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.status")
              }}</span>
              <span
                class="table-status"
                :class="`status_${WBSInfo?.status ? WBSInfo?.status : 1}`"
                >{{
                  statusOptions[WBSInfo?.status ? WBSInfo?.status : 1].label
                }}</span
              >
            </li>
            <li class="h-56px w-190px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.progress")
              }}</span>
              <el-progress
                :text-inside="true"
                :stroke-width="24"
                :percentage="WBSInfo?.schedule"
              />
            </li>
          </ul>
        </div>
        <el-tabs
          v-model="activeName"
          class="demo-tabs"
          @tab-click="handleTabClick"
        >
          <el-tab-pane name="first">
            <template #label>
              <span class="custom-tabs-label">
                <svg-icon
                  class="w-14px h-14px mr-5px text-[#969799]"
                  :icon-class="
                    activeName !== 'first'
                      ? 'wbs-info-no-selecte'
                      : 'wbs-info-selecte'
                  "
                />
                {{ $t("common.wbsInfo") }}
              </span>
            </template>

            <div
              class="flex h-52px px-16px py-15px border-rd-8px bg-[#F0F5FF] items-center text-[#323233] text-16px font-900"
            >
              <i class="i-ep:arrow-down w-1em h-1em mr-8px"></i
              >{{ $t("common.basicInfo") }}
            </div>
            <BasicInfoForm
              ref="basicInfoFormFormRef2"
              :disabled="viewType == 2 ? false : true"
              :projectInfo="projectInfo"
            />
            <div
              class="flex h-52px px-16px py-15px border-rd-8px bg-[#F0F5FF] items-center text-[#323233] text-16px font-900"
            >
              <i class="i-ep:arrow-down w-1em h-1em mr-8px"></i
              >{{ $t("common.systemInfo") }}
            </div>
            <SystemForm :systemInfo="systemInfo" />
          </el-tab-pane>
          <!-- 添加工具 -->
          <el-tab-pane name="second">
            <template #label>
              <span class="custom-tabs-label">
                <svg-icon
                  class="w-14px h-14px mr-5px text-[#969799]"
                  :icon-class="
                    activeName !== 'second'
                      ? 'addToolsNoSelect'
                      : 'addToolsSelect'
                  "
                />
                {{ $t("common.addTools") }}
              </span>
            </template>
            <!-- 列表 -->
            <AddTools
              ref="addToolsRef"
              :viewType="viewType"
              :productsData="productsData"
              :rentalData="rentalData"
              :wbsId="wbsId"
            />
          </el-tab-pane>
          <!-- 添加人员 -->
          <el-tab-pane name="third">
            <template #label>
              <span class="custom-tabs-label">
                <svg-icon
                  class="w-14px h-14px mr-5px text-[#969799]"
                  :icon-class="
                    activeName !== 'third'
                      ? 'addPersonnelNoSelect'
                      : 'addPersonnelSelect'
                  "
                />
                {{ $t("common.addPersonnel") }}
              </span>
            </template>
            <AddPersonnel
              ref="addPersonnelRef"
              :viewType="viewType"
              :userData="userData"
              :wbsId="wbsId"
            />
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <div class="dialog-footer" v-show="viewType == 2">
          <el-button type="primary" @click="handleDrawerSubmitClick">{{
            $t("common.save")
          }}</el-button>
          <el-button @click="handleDrawerCloseDialog">{{
            $t("common.cancel")
          }}</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { Search } from "@element-plus/icons-vue";
import WBSAPI from "@/api/wbs";
import contentConfig from "./config/content";
import {
  WBSProjectList,
  ProjectInfoForm,
  ISite,
  GoodsInfo,
  WbsUsersInfo,
  WBSInfoForm,
} from "@/api/wbs/model";
import type { IObject } from "@/hooks/usePage";
import type PageContent from "@/components/PageContent/index.vue";
import type { TabsPaneContext } from "element-plus";
import BasicInfoForm from "./components/BasicInfoForm/index.vue";
import AddTools from "./components/AddTools/index.vue";
import AddPersonnel from "./components/AddPersonnel/index.vue";
import UserAPI from "@/api/user";
defineOptions({
  name: "WBS",
  inheritAttrs: false,
});
const { t } = useI18n();

// 状态
const statusOptions = ref<Options[]>([
  {
    value: 0,
    label: t("common.toBegin"),
  },
  {
    value: 1,
    label: t("common.toBegin"),
  },
  {
    value: 2,
    label: t("common.haveInHand"),
  },
  {
    value: 3,
    label: t("common.completed"),
  },
  {
    value: 4,
    label: t("common.paused"),
  },
  {
    value: 5,
    label: t("common.expired"),
  },
]);

const searchName = ref("");
const handleSearch = () => {
  getProjectList();
};
const projectAndSite = ref<WBSProjectList[]>([]);
const queryParams = reactive<PageQuery>({
  page: 1,
  page_size: 1000000,
});
const getProjectList = () => {
  WBSAPI.projectsList({ ...queryParams, keyword: searchName.value }).then(
    (data) => {
      projectAndSite.value = data.list;
    }
  );
};
const siteId = ref("");
const projectId = ref("");
const wbsId = ref("");
const showInfo = ref(false);
const projectInfo = ref<WBSProjectList>();
const siteName = ref<any>("");
const contentRef = ref<InstanceType<typeof PageContent>>();
interface IDefaultParams {
  site_id: string;
  project_id: string;
}
const defaultParams = reactive<IDefaultParams>({ site_id: "", project_id: "" });

const handleSiteClick = (pitem: WBSProjectList, citem: ISite) => {
  console.log("%c Line:407 🥃 pitem", "color:#3f7cff", pitem);
  siteId.value = citem.id;
  projectId.value = pitem.id;
  defaultParams.site_id = citem.id;
  defaultParams.project_id = pitem.id;
  siteName.value = citem.s_name;
  const { id, p_name, p_no, status_text, status, process } = pitem;
  projectInfo.value = { id, p_name, p_no, status_text, status, process };
  showInfo.value = true;
  contentRef.value?.fetchPageData(
    {
      site_id: citem.id,
      project_id: pitem.id,
    },
    true
  ); //重置查询
};

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
const loading = ref(false);
// 新增
function handleOpenDialog() {
  dialog.visible = true;
  dialog.title = t("common.addWBS");
}
/** 关闭弹窗 */
const basicInfoFormFormRef = ref(ElForm);
function handleCloseDialog() {
  dialog.visible = false;
  basicInfoFormFormRef.value.wbsFormRef.resetFields();
  basicInfoFormFormRef.value.wbsFormRef.clearValidate();
  basicInfoFormFormRef.value.formData.id = undefined;
  basicInfoFormFormRef.value.formData.status = 1;
}

/** 提交表单 */
function handleSubmit() {
  basicInfoFormFormRef.value.wbsFormRef.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const Id = basicInfoFormFormRef.value.formData.id;
      basicInfoFormFormRef.value.formData.project_id = projectId.value;
      basicInfoFormFormRef.value.formData.site_id = siteId.value;
      WBSAPI.add({ wbs_info: basicInfoFormFormRef.value.formData })
        .then(() => {
          ElMessage.success(
            Id
              ? t("common.modifiedSuccessfully")
              : t("common.newSuccessfullyAdded")
          );
          handleCloseDialog();
          contentRef.value?.fetchPageData({}, true); //重置查询
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

// 弹窗
const drawerDialog = reactive({
  title: "",
  visible: false,
});

const activeName = ref("first");

const handleTabClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};
/** 关闭弹窗 */
const basicInfoFormFormRef2 = ref(ElForm);
function handleDrawerCloseDialog() {
  drawerDialog.visible = false;
  activeName.value = "first";
  basicInfoFormFormRef2.value.wbsFormRef.resetFields();
  basicInfoFormFormRef2.value.wbsFormRef.clearValidate();
  basicInfoFormFormRef2.value.formData.id = undefined;
  basicInfoFormFormRef2.value.formData.status = 1;
}

// 获取详情
const viewType = ref(2); //1: 查看 2:编辑
const systemInfo = ref<SystemForm | undefined>();
const projectInfoForm = ref<ProjectInfoForm>();
const WBSInfo = ref<WBSInfoForm>();
const productsData = ref<GoodsInfo[]>();
const rentalData = ref<GoodsInfo[]>();
const userData = ref<WbsUsersInfo[]>();
const getDetail = (row: IObject) => {
  drawerDialog.visible = true;
  drawerDialog.title = row.wbs_name;
  WBSAPI.detail({ id: row.id }).then((data) => {
    systemInfo.value = data.system_info;
    projectInfoForm.value = data.project_info;
    productsData.value = data.sale_goods;
    rentalData.value = data.lease_goods;
    userData.value = data.wbs_users;
    WBSInfo.value = data.wbs_info;
    WBSInfo.value.schedule = row.schedule;
    Object.assign(basicInfoFormFormRef2.value.formData, data.wbs_info);
  });
};
// 查看
const handleViewClick = (row: IObject) => {
  wbsId.value = row.id;
  viewType.value = 1;
  getDetail(row);
};

// 编辑
const handleEditClick = (row: IObject) => {
  wbsId.value = row.id;
  viewType.value = 2;
  getDetail(row);
};

// 编辑保存
const addPersonnelRef = ref(ElForm);
const addToolsRef = ref(ElForm);
const handleDrawerSubmitClick = () => {
  basicInfoFormFormRef2.value.wbsFormRef.validate((valid: any) => {
    const sale_goods = addToolsRef.value.newProductsData;
    const lease_goods = addToolsRef.value.newRentalData;
    const wbs_users = addPersonnelRef.value.newUserData;
    if (
      (sale_goods.length > 0 &&
        sale_goods.some((item: any) => item.asset_id === "")) ||
      (lease_goods.length > 0 &&
        lease_goods.some((item: any) => item.asset_id === "")) ||
      (wbs_users.length > 0 &&
        wbs_users.some((item: any) => item.user_ref === ""))
    ) {
      ElMessage.error(t("common.pleaseFillFirst"));
      return;
    }
    if (valid) {
      loading.value = true;
      const Id = basicInfoFormFormRef2.value.formData.id;
      basicInfoFormFormRef2.value.formData.project_id = projectId.value;
      basicInfoFormFormRef2.value.formData.site_id = siteId.value;
      WBSAPI.add({
        wbs_info: basicInfoFormFormRef2.value.formData,
        sale_goods: sale_goods.map((item: any) => {
          return {
            id: item.id == "-1" ? undefined : item.id,
            asset_id: item.asset_id,
            unit_price: item.unit_price,
            num: item.num,
          };
        }),
        lease_goods: lease_goods.map((item: any) => {
          return {
            id: item.id == "-1" ? undefined : item.id,
            asset_id: item.asset_id,
            unit_price: item.unit_price,
            num: item.num,
            days: item.days,
          };
        }),
        wbs_users: wbs_users.map((item: any) => {
          return {
            id: item.id == "-1" ? undefined : item.id,
            user_id: item.user_ref,
            daily_wage: item.daily_wage,
            days: item.days,
          };
        }),
      })
        .then(() => {
          ElMessage.success(
            Id
              ? t("common.modifiedSuccessfully")
              : t("common.newSuccessfullyAdded")
          );
          handleDrawerCloseDialog();
          contentRef.value?.fetchPageData({}, true); //重置查询
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      activeName.value = "first";
      ElMessage.error(t("common.completeInfo"));
    }
  });
};

const stakeholderObj = reactive<{ [key: string]: string }>({});
const getUserList = async () => {
  const data = await UserAPI.getPage({
    page: 1,
    page_size: 10000,
  });
  if (data.list.length > 0) {
    data.list.forEach((item) => {
      stakeholderObj[item.id] = item.nickname as string;
    });
  }
};

onMounted(() => {
  getProjectList();
  getUserList();
});
</script>

<style lang="scss" scoped>
:deep(.el-empty) {
  padding: 10px !important;
}

:deep(.el-loading-mask) {
  background: none !important;
}

.custom-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 900;
  color: #323233;
  text-transform: capitalize;

  &::before {
    display: inline-block;
    width: 3px;
    height: 22px;
    margin-right: 8px;
    content: "";
    background: #4e6bef;
  }
}

:deep(.el-menu) {
  border: none !important;

  .el-sub-menu {
    padding: 0 !important;

    & > .el-sub-menu__title {
      padding: 0 24px 0 14px !important;
      font-size: 14px;
      color: #323233;

      .el-sub-menu__icon-arrow {
        right: 10px !important;
      }
    }

    &.is-opened {
      .el-sub-menu__title {
        color: #fff;
        background: #4e6bef;
      }
    }

    .el-menu {
      padding-top: 8px !important;
    }

    .el-menu-item {
      display: block !important;
      padding: 0 14px !important;
      margin-bottom: 8px !important;
      border: none !important;

      &.is-active {
        color: #4e6bef !important;
        background: #f0f5ff !important;
      }

      &:hover {
        background: #f0f5ff !important;
      }
    }
  }
}
</style>
